package com.ruoyi.web.controller.app;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.domain.AppChatRecord;
import com.ruoyi.system.domain.AppUserRelation;
import com.ruoyi.system.service.IAppChatRecordService;
import com.ruoyi.system.service.IAppUserRelationService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/app/callback")
@Api("腾讯IM回调接口")
public class ForTencentImCallbackController {

    @Autowired
    private IAppChatRecordService iAppChatRecordService;
    @Autowired
    private IAppUserRelationService appUserRelationService;

    @Value("${IMConfig.sdkAppId}")
    private long sdkAppId;

    @RequestMapping(value = "acceptInfo", method = {RequestMethod.POST})
    public JSONObject imEventCallback(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        JSONObject returnJson = new JSONObject();
        Map map = new HashMap();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        System.out.println("____map:" + JSONObject.toJSONString(map));
        System.out.println("____jsonObject:" + JSONObject.toJSONString(jsonObject));
        String callbackCommand = map.get("CallbackCommand").toString(); // 回调命令
        String sdkAppid = map.get("SdkAppid").toString(); // SdkAppid(校验一下是否是自己的账户的消息)
        if (String.valueOf(sdkAppId).equals(sdkAppid) && jsonObject != null && jsonObject.size() > 0) { // 如果不是自己账户的消息就丢弃
            // 单聊消息回调
            if ("C2C.CallbackAfterSendMsg".equals(callbackCommand)) {
                // 这里写保存单聊消息到自己数据库代码
                AppChatRecord info = new AppChatRecord();
                info.setCreateTime(new Date());
                info.setState(0L);
                info.setCallbackCommand(jsonObject.getString("CallbackCommand"));
                info.setFromAccount(jsonObject.getString("From_Account"));
                info.setToAccount(jsonObject.getString("To_Account"));
                info.setMsgSeq(jsonObject.getLong("MsgSeq"));
                info.setMsgRandom(jsonObject.getLong("MsgRandom"));
                info.setMsgTime(jsonObject.getLong("MsgTime"));
                info.setMsgKey(jsonObject.getString("MsgKey"));
                info.setOnlineOnlyFlag(jsonObject.getLong("OnlineOnlyFlag"));
                info.setSendMsgResult(jsonObject.getLong("SendMsgResult"));
                info.setErrorInfo(jsonObject.getString("ErrorInfo"));
                info.setUnreadMsgNum(jsonObject.getLong("UnreadMsgNum"));
                info.setMsgBody(jsonObject.getString("MsgBody"));
                info.setCloudCustomData(jsonObject.getString("CloudCustomData"));
                iAppChatRecordService.insertAppChatRecord(info);
            }
            if ("Sns.CallbackFriendAdd".equals(callbackCommand)) {
                System.out.println(">>>>>>>>>:添加好友");
                // 先判断是否已经添加过好友
                JSONArray jsonArray = jsonObject.getJSONArray("PairList");
                if (!jsonArray.isEmpty()) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        System.out.println(">>>>>>>>>:添加好友");
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        AppUserRelation appUserRelation = new AppUserRelation();
                        appUserRelation.setUserId(jsonObject1.getLong("From_Account"));
                        appUserRelation.setFriendId(jsonObject1.getLong("To_Account"));
                        List<AppUserRelation> list = appUserRelationService.selectAppUserRelationList(appUserRelation);
                        if (list.isEmpty()) {
                            // 添加好友
                            appUserRelationService.insertAppUserRelation(appUserRelation);
                        }
                    }
                }


            }
            if ("Sns.CallbackFriendDelete".equals(callbackCommand)) {
                System.out.println(">>>>>>>>>:删除好友");
                // 删除好友
                JSONArray jsonArray = jsonObject.getJSONArray("PairList");
                if (!jsonArray.isEmpty()) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        AppUserRelation appUserRelation = new AppUserRelation();
                        appUserRelation.setUserId(jsonObject1.getLong("From_Account"));
                        appUserRelation.setFriendId(jsonObject1.getLong("To_Account"));
                        List<AppUserRelation> list = appUserRelationService.selectAppUserRelationList(appUserRelation);
                        for (AppUserRelation info : list) {
                            appUserRelationService.deleteAppUserRelationById(info.getId());
                        }
                    }

                }

            }
        }
        // 接收完回调消息后，返回接收成功应答包给IM（无论成功或者失败，都要响应应答包给IM）
        // 因为为了不影响发言，回调失败也响应回调成功，如果业务要求严格，需要做失败处理，具体参考腾讯云IM接口文档。
        returnJson.put("ActionStatus", "OK");
        returnJson.put("ErrorInfo", "");
        returnJson.put("ErrorCode", 0);
        return returnJson;
    }


}
